<?php

namespace App\Https\Controllers;

use App\Utils\Utils;
use App\Utils\ImgCompress;
use Core\Https\Controller;

class TaskController extends Controller
{
    private $upload_dir = "static/resources";
    function __construct()
    {
        parent::__construct();
        $this->code = 200;
        $this->initDB(array("dbname" => "blog"));
    }
    public function userList($params)
    {
        if (isset($params['user_id'])) {
            $user_id = $params['user_id'];
            $sql = "SELECT * FROM blog_user WHERE user_id='$user_id'";
            $userList = mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            return $this->json($userList);
        } else {
            $sql = "SELECT * FROM blog_user";
            $userList = mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            return $this->json($userList);
        }
    }
    public function updateUserScore($params)
    {
        $user_id = $params['user_id'];
        $score = $params['score'];
        $sql = "SELECT * FROM blog_user WHERE user_id='$user_id'";
        $user = mysqli_fetch_assoc($this->db->db_query($sql));
        $totalScore = $user['score'] + $score;
        $sql = "UPDATE blog_user SET score=$totalScore WHERE user_id = '$user_id'";
        $res = $this->db->db_query($sql);
        $this->code =  $res ? 200 : 400;
        return $this->json();
    }
    // 获取任务列表
    public function taskList($params)
    {
        $user_id = $params['user_id'];
        $status = $params['status'] ?? 0;
        if (isset($params['id'])) {
            $id = $params['id'];
            $sql = "SELECT * FROM market_task WHERE id=$id AND user_id='$user_id' AND status=$status";
            $task = mysqli_fetch_assoc($this->db->db_query($sql));
            return $this->json($task);
        } else {
            $pageCount = ceil($this->getTaskCount($user_id, "market_task") / 10);
            $pageNum = $params['pageNum'] ?? 1;
            $offSET = ($pageNum - 1) * 10;
            $WHERE = "market_task.deleted_on = 0 AND market_task.user_id = '$user_id' AND market_task.status = $status";
            $sql = "SELECT market_task.*,blog_tag.name as category_name FROM market_task INNER JOIN blog_tag ON blog_tag.id = market_task.category_id WHERE $WHERE order by market_task.created_on desc limit 10 offSET $offSET";
            $tasks =  mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            $result = array("pageNum" => $pageCount, "tasks" => $tasks);
            return $this->json($result);
        }
    }
    function getTaskCount($user_id, $table_name)
    {
        $sql = "SELECT Count(id) as count FROM $table_name WHERE deleted_on = 0 AND user_id = '$user_id'";
        $res = mysqli_fetch_assoc($this->db->db_query($sql));
        $count = $res['count'];
        return (int)$count;
    }
    // 添加任务
    public function addTask($params)
    {
        $title = $params['title'];
        $intro = $params['intro'];
        $score = $params['score'];
        $user_id = $params['user_id'];
        $category_id = $params['category_id'];
        $status = $params['status'] ?? 0;
        $created_on = Utils::getTimestamp();
        if ($title && $intro && $score && $category_id) {
            $value = "'$user_id','$title','$intro',$score,$status,$category_id,'$created_on'";
            $sql = "INSERT INTO market_task (user_id,title,intro,score,status,category_id,created_on) VALUES ($value)";
            $res = $this->db->db_query($sql);
            if ($res) {
                return $this->json();
            } else {
                $this->taskError();
            }
        } else {
            $this->taskError();
        }
    }
    // 修改任务
    public function editTask($params)
    {
        $title = $params['title'];
        $intro = $params['intro'];
        $score = $params['score'];
        $status = $params['status'];
        $category_id = $params['category_id'];
        $user_id = $params['user_id'];
        if ($title && $intro && $score && $status && $category_id) {
            $sql = "UPDATE market_task SET title='$title',intro='$intro',score=$score,category_id='$category_id',status=$status WHERE user_id = '$user_id'";
            $res = $this->db->db_query($sql);
            $this->code =  $res ? 200 : 400;
            return $this->json();
        } else {
            $this->taskError();
        }
    }
    // 更新任务状态
    public function editTaskStatus($params)
    {
        $id = $params['id'];
        $status = $params['status'];
        $user_id = $params['user_id'];
        $score = $params['score'];
        if ($id && $status) {
            $sql = "UPDATE market_task SET status=$status WHERE id=$id AND user_id = '$user_id'";
            $res = $this->db->db_query($sql);
            $this->code =  $res ? 200 : 400;
            if ($res) {
                return $this->updateUserScore($params);
            } else {
                $this->taskError();
                return $this->json();
            }
        } else {
            $this->taskError();
            return $this->json();
        }
    }
    // 删除任务
    public function removeTask($params)
    {
        if (isset($params['id'])) {
            $p_id = $params['id'];
            $time = Utils::getTimestamp();
            $user_id = $params['user_id'];
            $sql = "UPDATE market_task SET deleted_on =$time WHERE id = $p_id AND user_id='$user_id'";
            $res = $this->db->db_query($sql);
            $this->code =  $res ? 200 : 400;
            return $this->json();
        } else {
            $this->taskError();
        }
    }
    public function categoryList($params)
    {
        $type = $params['type'];
        $user_id = $params['user_id'];
        if (empty($user_id)) {
            $this->taskError();
        }
        $sql = "SELECT * FROM blog_tag WHERE type = '$type' AND deleted_on = 0 AND user_id = '$user_id' order by created_on desc";
        $res = mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
        $this->code =  $res ? 200 : 400;
        return $this->json($res);
    }
    // 商品列表
    public function goodsList($params)
    {
        $user_id = $params['user_id'];
        if (isset($params['id'])) {
            $id = $params['id'];
            $sql = "SELECT * FROM market_goods WHERE id = {$id} AND deleted_on = 0 AND user_id = '$user_id'";
            $task = mysqli_fetch_assoc($this->db->db_query($sql));
            return $this->json($task);
        } else {
            $pageCount = ceil($this->getTaskCount($user_id, "market_goods") / 10);
            $pageNum = $params['pageNum'] ?? 1;
            $offSET = ($pageNum - 1) * 10;
            $sql = "SELECT * FROM market_goods WHERE deleted_on = 0 AND user_id = '$user_id' order by market_goods.created_on desc limit 10 offSET $offSET";
            $goodsList =  mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            $result = array("pageNum" => $pageCount, "goods" => $goodsList);
            return $this->json($result);
        }
    }
    /// 获取商品状态列表
    public function goodsStatusList($params)
    {
        $user_id = $params['user_id'];
        $status = $params['status'] ?? 0;
        if (isset($params['id'])) {
            $id = $params['id'];
            $sql = "SELECT * FROM market_order WHERE id = {$id} AND deleted_on = 0 AND user_id = '$user_id' AND status=$status  ";
            $task = mysqli_fetch_assoc($this->db->db_query($sql));
            return $this->json($task);
        } else {
            $pageCount = ceil($this->getTaskCount($user_id, "market_order") / 10);
            $pageNum = $params['pageNum'] ?? 1;
            $offSET = ($pageNum - 1) * 10;
            $sql = "SELECT * FROM market_order INNER JOIN market_goods ON market_goods.id = market_order.goods_id WHERE market_order.deleted_on = 0 AND market_order.user_id = '$user_id' AND market_order.status = $status ORDER BY market_order.buytime DESC LIMIT 10 OFFSET $offSET";
            $goodsList =  mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            $result = array("pageNum" => $pageCount, "goods" => $goodsList);
            return $this->json($result);
        }
    }
    // 添加商品
    public function addGoods($params)
    {
        if (isset($params['id'])) {
            $p_id = $params['id'];
            $time = Utils::getTimestamp();
            $user_id = $params['user_id'];
            $sql = "UPDATE market_goods SET deleted_on =$time WHERE id = $p_id AND user_id='$user_id'";
            $res = $this->db->db_query($sql);
            $this->code =  $res ? 200 : 400;
            return $this->json();
        } else {
            $this->taskError();
        }
    }
    // 购买商品
    public function buyGoods($params)
    {
        if (isset($params['goods_id'])) {
            $time = Utils::getTimestamp();
            $user_id = $params['user_id'];
            $goods_id = $params['goods_id'];
            $value = "$goods_id,'$user_id',$time";
            $sql = "INSERT INTO market_order (goods_id,user_id,buytime) VALUES ($value)";
            $res = $this->db->db_query($sql);
            $this->code =  $res ? 200 : 400;
            return $this->json();
        } else {
            $this->taskError();
        }
    }
    // 删除商品
    public function removeGoods($params)
    {
        $time = Utils::getTimestamp();
        if (isset($params['id'])) {
            $g_id = $params['id'];
            $user_id = $params['user_id'];
            $sql = "UPDATE market_goods SET deleted_on =$time WHERE id = $g_id AND user_id='$user_id'";
            $res = $this->db->db_query($sql);
            $this->code =  $res ? 200 : 400;
            return $this->json();
        } else {
            $this->taskError();
        }
    }
    // 上传图片
    public function uploadGoodsCover($params)
    {
        // 上传图片
        if (empty($_FILES)) die();
        $files = $_FILES;
        $file = $files[array_key_first($files)];
        $type = array("jpg", "gif", "jpeg", "png");

        $img_name = Utils::uuid();
        // 判断上传文件类型
        $file_type = strtolower(pathinfo($img_name, PATHINFO_EXTENSION));
        if (!in_array($file_type, $type)) {
            return;
        }
        $file_path = "{$this->upload_dir}/images/{$img_name}";
        $img_url = "{$_SERVER["HTTP_ORIGIN"]}/{$file_path}?t=" . Utils::getTimestamp();
        if (move_uploaded_file($file['tmp_name'], $file_path)) {
            $imgCompress = new ImgCompress($file_path, 0.5);
            $imgCompress->compressImg($file_path);
            return $this->json(array("url" => $img_url));
        } else {
            $this->taskError("文件上传失败");
        }
    }
    function taskError($msg = '参数错误')
    {
        $this->code =  400;
        $this->msg = "参数错误";
        return $this->json();
    }
}
